<template>
  <view class="bank-add-container">
    <u-navbar title="添加银行卡" :autoBack="true"></u-navbar>

    <view class="form-container">
      <u-form :model="formData" :rules="rules" ref="formRef">
        <u-form-item label="银行名称" prop="bank_name">
          <u-input v-model="formData.bank_name" placeholder="请输入银行名称" />
        </u-form-item>

        <u-form-item label="银行卡号" prop="code">
          <u-input
            v-model="formData.code"
            placeholder="请输入银行卡号"
            type="number"
            maxlength="19"
          />
        </u-form-item>
      </u-form>

      <view class="submit-btn">
        <u-button type="primary" @click="handleSubmit">确认添加</u-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue";
import { addBank } from "@/common/apis/user.js";

const formData = ref({
  bank_name: "",
  code: "",
});

const rules = ref({
  bank_name: [
    { required: true, message: "请输入银行名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在2到20个字符", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入银行卡号", trigger: "blur" },
    { pattern: /^\d{16,19}$/, message: "请输入16-19位数字", trigger: "blur" },
  ],
});

const formRef = ref(null);

async function handleSubmit() {
  try {
    await formRef.value.validate();
    const response = await addBank(formData.value);
    uni.showToast({
      title: "添加成功",
      icon: "success",
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } catch (error) {
    console.error("添加失败:", error);
    uni.showToast({
      title: error.message || "添加失败",
      icon: "none",
    });
  }
}
</script>

<style lang="scss" scoped>
.bank-add-container {
  padding: 20rpx;

  .form-container {
    margin-top: 40rpx;
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
  }

  .submit-btn {
    margin-top: 60rpx;
  }
}
</style>
